ZigZag Conversion
August 19, 2016
It took me some time to understand the problem but as soon as I figured out what it was asking, all I had to do was find a pattern and the solution became clear.
Full Solution in Java:
public class Solution { public String convert(String s, int numRows) { StringBuilder sb = new StringBuilder(); char[] c = s.toCharArray(); int stepOne = 0; int stepTwo = 0; if(numRows==1){ return s; } for(int i=1; i<=numRows; i++){ if(i==1 || i==numRows){ stepOne = 2*(numRows-1); stepTwo = 2*(numRows-1); } else{ stepOne = 2*(numRows-i); stepTwo = 2*(i-1); } int pos = i-1; for(int j=0; j< c.length; j++){ if(pos>=c.length){ break; } if(j%2==0){ sb.append(c[pos]); pos+=stepOne; } else{ sb.append(c[pos]); pos+=stepTwo; } } } return sb.toString(); } }